/**
 * @description 表单
 * @author chengpeng
 */

import React, { Component } from 'react';
import axios from 'axios'
import * as RecordsApi from '../utils/RecordsApi'

export default class RecordFrom extends Component {
    constructor() {
        super()
        this.state = {
            date: "", // 2020-02-20
            title: "",
            amount: ""
        }
    }

    handleChange(e) {
        let name = e.target.name, obj
        this.setState((
            obj = {},
            obj["" + name] = e.target.value,
            obj
        ))
    }

    handleSubmit(e) {
        e.preventDefault();
        axios.post(`${RecordsApi.api}/api/create.json`, {
            date: this.state.date,
            title: this.state.title,
            amount: Number.parseInt(this.state.amount)
        }).then(res => {
            if(res.status === 200 && res.data.errCode === 0) {
                // 添加成功返回新增数据 减少接口请求
                this.props.handleNewRecord(res.data)
                this.setState = {
                    date: "",
                    title: "",
                    amount: ""
                }
            } else {
                alert(res.data.errMsg)
                return
            }
        })
    }

    valid() {
        return this.state.date && this.state.title && this.state.amount
    }

    render() {
        return (
            <form className="form-inline mb-3" onSubmit={this.handleSubmit.bind(this)}>
                <div className="form-group mr-1">
                    <input type="date" className="form-control" onChange={this.handleChange.bind(this)} placeholder="Date" name="date" value={this.state.date} />
                </div>
                <div className="form-group mr-1">
                    <input type="text" className="form-control" onChange={this.handleChange.bind(this)} placeholder="Title" name="title" value={this.state.title} />
                </div>
                <div className="form-group mr-1">
                    <input type="number" className="form-control" onChange={this.handleChange.bind(this)} placeholder="Amount" name="amount" value={this.state.amount} />
                </div>
                <button className="btn btn-primary" disabled={!this.valid()}>Create Record</button>
            </form>
        );
    }
}